﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace RichFrame
{
    /// <summary>
    /// 自定义动画
    /// </summary>
    public abstract class CustomAnimation : MonoBehaviour
    {
        public bool playOnStart;
        public float playDelay;
        public float duration;
        public bool loop;
        public AnimationCurve animationCurve;
        public bool animating
        {
            get
            {
                return _enableAnim;
            }
        }
        public float timer;
        protected bool _enableAnim = false;


        protected virtual void Update()
        {
            if (_enableAnim)
            {
                if (timer < duration)
                {
                    UpdateAnimation(timer / duration);
                    timer += Time.deltaTime;
                }
                else
                {
                    timer = 0;
                    if (!loop)
                    {
                        _enableAnim = false;
                    }
                }
            }
        }

        public virtual void StartAnimation()
        {
            ResetAnim();
            if (playDelay > 0)
            {
                Invoke("EnableAnim", playDelay);
            }
            else
            {
                EnableAnim();
            }
        }

        public virtual void StopAnimation()
        {
            ResetAnim();
        }

        protected virtual void ResetAnim()
        {
            timer = 0;
            _enableAnim = false;
            UpdateAnimation(0);
            CancelInvoke("EnableAnim");
        }

        protected void EnableAnim()
        {
            _enableAnim = true;
        }

        protected virtual void OnEnable()
        {
            if (playOnStart)
            {
                StartAnimation();
            }
        }

        protected virtual void OnDisable()
        {
            ResetAnim();
        }

        protected abstract void UpdateAnimation(float v);
    }
}
